/*
 * Copyright (C) 2012-2013  Romain DUBOIS
 * 
 * This file is part of NeMoS - Network and Modular Software
 * 
 * NeMoS is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * NeMoS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with NeMoS.  If not, see <http://www.gnu.org/licenses/>.
 */
package nemos.remote.event;

import java.util.concurrent.atomic.AtomicReference;

import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.ReferencePolicy;
import org.apache.felix.scr.annotations.Service;
import org.osgi.framework.Constants;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;

/**
 * EventBroadcasterImpl : The auto-deployed {@link IEventBroadcaster}
 * implementation.
 * 
 * @author Romain DUBOIS
 */
@Service(IEventBroadcaster.class)
@Property(name = Constants.SERVICE_EXPORTED_INTERFACES, value = "*")
@Component
public class EventBroadcasterImpl implements IEventBroadcaster {

    /** The event admin service */
    @Reference(name = "eventAdmin", cardinality = ReferenceCardinality.OPTIONAL_UNARY, policy = ReferencePolicy.DYNAMIC, referenceInterface = EventAdmin.class)
    private final AtomicReference<EventAdmin> mEventAdmin;

    /**
     * Constructor.
     */
    public EventBroadcasterImpl() {
        super();
        mEventAdmin = new AtomicReference<EventAdmin>();
    }

    /**
     * {@inheritDoc}
     * 
     * @see nemos.remote.event.IEventBroadcaster#broadcastEvent(org.osgi.service.event.Event)
     */
    @Override
    public void broadcastEvent(final Event pEvent) {
        final EventAdmin lAdmin = mEventAdmin.get();
        if (lAdmin != null) {
            lAdmin.postEvent(pEvent);
        }
    }

    /**
     * Change the event admin.
     * 
     * @param pEventAdmin
     *            The event admin to set
     */
    public void bindEventAdmin(final EventAdmin pEventAdmin) {
        mEventAdmin.set(pEventAdmin);
    }

    /**
     * Remove the event admin.
     * 
     * @param pEventAdmin
     *            The event admin to remove
     */
    public void unbindEventAdmin(final EventAdmin pEventAdmin) {
        mEventAdmin.compareAndSet(pEventAdmin, null);
    }
}
